package gazpachito.examples.patterns.methodTemplate.service;

import gazpachito.examples.patterns.methodTemplate.api.TemplateDTO;
import gazpachito.examples.patterns.methodTemplate.api.VehicleDTO;
import gazpachito.examples.patterns.methodTemplate.api.enums.VehicleEnum;
import gazpachito.examples.patterns.methodTemplate.business.TemplateBusiness;
import gazpachito.examples.patterns.methodTemplate.business.exceptions.BusinessException;
import gazpachito.examples.patterns.methodTemplate.business.exceptions.FacadeException;
import gazpachito.examples.patterns.methodTemplate.factory.TemplateServiceLocator;
import gazpachito.examples.patterns.methodTemplate.utils.MessageUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * An implementation about VehicleFacade to manage vehicles using a template
 * 
 * @author jvillar
 * 
 */
@Component
public class VehicleFacadeImpl implements VehicleFacade {

	@Autowired
	private TemplateServiceLocator templateServiceLocator;

	@Override
	public void manageVehicle(VehicleDTO vehicle, VehicleEnum template)
			throws FacadeException {

		if (template == null) {

			throw new FacadeException(
					MessageUtils
							.getMessage(MessageUtils.ERROR_TEMPLATE_NOT_INFORMED));

		}

		@SuppressWarnings("unchecked")
		TemplateBusiness<TemplateDTO> templateBusiness = this.templateServiceLocator
				.getTemplate(template.getService());

		try {
			templateBusiness.validate(vehicle);
			templateBusiness.execute(vehicle);
		} catch (BusinessException b) {
			throw new FacadeException(
					MessageUtils.getMessage(MessageUtils.ERROR_VEHICLE_WRONG),
					b);
		}

	}

}
